package com.chenzouquan.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * 文件工具类
 */
public class FileUtil {

    /**
     * 文件路径
     */
    private static final String PATH = "src/main/resources/file";

    /**
     * 文件上传函数
     * @param sourceFile 上传源文件
     * @throws IOException
     */
    public String uploadFile(File sourceFile) throws IOException {
        File destFile = new File(PATH + File.separator + sourceFile.getName());
        if (destFile.exists()){
            // 返回上传文件路径
            return PATH + File.separator + sourceFile.getName();
        }
        FileInputStream in = new FileInputStream(sourceFile);
        FileOutputStream out = new FileOutputStream(destFile);

        byte[] buffer = new byte[1024];
        int bytesRead = 0;
        while ((bytesRead = in.read(buffer)) != -1) {
            out.write(buffer, 0, bytesRead);
        }

        in.close();
        out.close();

        // 返回上传文件路径
        return PATH + File.separator + sourceFile.getName();
    }
}
